package utils

import (
	"fmt"
	"time"
)

// FormatBytes 格式化字节数为人类可读的字符串
func FormatBytes(bytes uint64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := uint64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}

// FormatBytesFloat 格式化浮点字节数为人类可读的字符串
func FormatBytesFloat(bytes float64) string {
	const unit = 1024.0
	if bytes < unit {
		return fmt.Sprintf("%.1f B", bytes)
	}
	
	units := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
	exp := 0
	for bytes >= unit && exp < len(units)-1 {
		bytes /= unit
		exp++
	}
	return fmt.Sprintf("%.1f %s", bytes, units[exp])
}

// FormatSpeed 格式化速度为Mbps字符串
func FormatSpeed(bps float64) string {
	mbps := bps * 8 / 1024 / 1024
	if mbps < 1.0 {
		kbps := bps * 8 / 1024
		if kbps < 1.0 {
			return fmt.Sprintf("%.0f bps", bps*8)
		}
		return fmt.Sprintf("%.1f Kbps", kbps)
	}
	if mbps < 1000 {
		return fmt.Sprintf("%.1f Mbps", mbps)
	}
	gbps := mbps / 1000
	return fmt.Sprintf("%.2f Gbps", gbps)
}

// FormatPercentage 格式化百分比
func FormatPercentage(value float64) string {
	if value < 0.01 {
		return "0%"
	}
	if value < 1.0 {
		return fmt.Sprintf("%.2f%%", value)
	}
	return fmt.Sprintf("%.1f%%", value)
}

// FormatTime 格式化时间为字符串
func FormatTime(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

// FormatTimeNow 格式化当前时间为字符串
func FormatTimeNow() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// FormatCount 格式化数量（如丢包数、连接数等）
func FormatCount(count uint64) string {
	if count < 1000 {
		return fmt.Sprintf("%d", count)
	}
	if count < 1000000 {
		return fmt.Sprintf("%.1fK", float64(count)/1000)
	}
	if count < 1000000000 {
		return fmt.Sprintf("%.1fM", float64(count)/1000000)
	}
	return fmt.Sprintf("%.1fB", float64(count)/1000000000)
}